package com.hnhcyy.goods.api;

import java.util.ArrayList;
import java.util.List;

import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.data.elasticsearch.core.query.UpdateQuery;
import org.springframework.data.elasticsearch.core.query.UpdateQueryBuilder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.hnhcyy.goods.pojo.Goods;

/**
 * 搜索
 * @author sheyongjun  
 * @date 2019年4月11日
 */
//@RestController
@RequestMapping("/search")
public class EsApi {
	
	@Autowired
	private ElasticsearchTemplate elasticsearchTemplate;

	/**
	 * 新增数据（单条）
	 * @author sheyongjun
	 * @date 2019年4月11日
	 */
	@RequestMapping("/save")
	public String save() {
		Goods goods = new Goods();
		goods.setSpid("SPH00000001");
		goods.setSpmch("化瘀固精合剂（乐赛仙）");
		goods.setShpchd("新疆奇康哈博维药股份有限公司");

		IndexQuery indexQuery = new IndexQueryBuilder()
				.withObject(goods).build();

		String index = this.elasticsearchTemplate.index(indexQuery);
		return index;
	}
	
	/**
	 * 批量出入数据
	 * @author sheyongjun
	 * @date 2019年4月11日
	 */
	@RequestMapping("/bulksave")
	public String bulkSave() {
		List<IndexQuery> list = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            Goods goods = new Goods();
            goods.setSpid("10000" + i);
            goods.setSpmch("测试" + i);
            goods.setShpchd( i + "有限公司");
            IndexQuery indexQuery = new
                    IndexQueryBuilder().withObject(goods).build();
            list.add(indexQuery);
        }
        Long start = System.currentTimeMillis();
        this.elasticsearchTemplate.bulkIndex(list);
        System.out.println("用时：" + (System.currentTimeMillis() - start));
		return null; 
	}
	
	/**
	 * 局部更新，全部更新使用index覆盖即可
	 * @author sheyongjun
	 * @date 2019年4月11日
	 */
	@RequestMapping("/update")
    public String update() {
        IndexRequest indexRequest = new IndexRequest();
        indexRequest.source("spmch", "化瘀固精");

        UpdateQuery updateQuery = new UpdateQueryBuilder()
                .withId("SPH00000001")
                .withClass(Goods.class)
                .withIndexRequest(indexRequest).build();

        return this.elasticsearchTemplate.update(updateQuery).getId();
    }

	/**
	 * 删除单条
	 * @author sheyongjun
	 * @date 2019年4月11日
	 */
	@RequestMapping("/delete/{id}")
    public String delete(@PathVariable("id") String id) {
        String returnId = this.elasticsearchTemplate.delete(Goods.class, id);
        return returnId;
    }
	
	/**
	 * 搜索
	 * @author sheyongjun
	 * @date 2019年4月11日
	 */
	@RequestMapping("/search")
    public void search() {
        PageRequest pageRequest = PageRequest.of(1, 10); //设置分页参数

        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.matchQuery("spmch", "化瘀固精")) // match查询
//                .withPageable(pageRequest)
                .build();

        AggregatedPage<Goods> goodsList =
                this.elasticsearchTemplate.queryForPage(searchQuery, Goods.class);

        System.out.println("总页数：" + goodsList.getTotalPages()); //获取总页数

        for (Goods goods : goodsList.getContent()) { // 获取搜索到的数据
            System.out.println(goods);
        }
    }
}
